<template>
  <div class="employees">
    <div class="app-container">

      <PageTools>
        <el-button v-if="$check('POINT-USER-EXPORT')" :loading="downloadLoading" style="margin:0 0 20px 20px;" size="small" type="success" icon="el-icon-document" @click="handleDownload">
          导出
        </el-button>
        <el-button v-if="$check('POINT-USER-IMPORT')" type="primary" size="small" @click="$router.push('/import?type=employee')">导入</el-button>
        <el-button v-if="$check('POINT-USER-ADD')" type="primary" size="small" icon="el-icon-plus" @click="showDialog = true">添加员工</el-button>
        <!-- <template v-slot:tips> haha</template>  具名插槽 -->
      </PageTools>
      <el-card v-loading="loading" style="margin-top:10px">
        <!-- 插入数据 -->
        <el-table border :data="list">
          <el-table-column label="序号" type="index" align="center" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" align="center" />
          <el-table-column label="头像" align="center">
            <template v-slot="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width: 100px; height: 100px; border-radius:50%"
                @click="addCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" align="center" />
          <el-table-column label="聘用形式" prop="formOfEmployment" align="center" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable prop="departmentName" align="center" />
          <!-- 4.格式化 入职时间 -->
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | dateFormat }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable prop="enableState" align="center">
            <template v-slot="{ row }">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="addRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[8, 16, 24, 32]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 对话框 -->
      <AddEmployee :show-dialog.sync="showDialog" @addEmp="addEmp" />
      <!-- 显示二维码 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="canvas" />
        </el-row>
      </el-dialog>
      <!-- 显示添加角色 -->
      <AssignRole :user-id="userId" :show-role-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import AddEmployee from './components/AddEmployee.vue'
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import qrcode from 'qrcode'
import AssignRole from './components/AssignRole.vue'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 8,
      total: 0,
      loading: false,
      showDialog: false,
      downloadLoading: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    // 1.获取所有员工列表
    this.getEmployeesList()
  },
  methods: {
    // 1.获取所有员工列表
    async getEmployeesList() {
      this.loading = true
      const { total, rows } = await getEmployeesList(this.page, this.size)
      // console.log(rows)
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleCurrentChange(value) {
      this.page = value
      this.getEmployeesList()
    },
    handleSizeChange(value) {
      this.size = value
      this.page = 1
      this.getEmployeesList()
    },
    // 2.处理序号
    indexMethod(val) {
      return val + 1 + (this.page - 1) * this.size
    },
    // 3.格式化聘用格式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : ''
    },
    // 4.删除员工
    async del(id) {
      try {
        await this.$confirm('你确定删除吗?', '温馨提示', {
          type: 'warning'
        })
      } catch {
        return
      }
      // 删除调用接口
      await delEmployee(id)
      this.$message.success('删除成功')
      // 如果删除的数据 是当前页面最后一条数据那么 此时当前页码 是大于2 的就让当前页面 -1
      if (this.list.length === 1 && this.page > 1) {
        this.page--
      }
      // 重新渲染数据
      this.getEmployeesList()
      //
    },
    addEmp() {
      this.showDialog = false
      // 跳转到添加页面
      // 重新渲染
      this.total++
      this.page = Math.ceil(this.total / this.size)
      this.getEmployeesList()
    },
    // 处理导出
    async handleDownload() {
      this.downloadLoading = true
      // 获取到所有员工
      const res = await getEmployeesList(1, this.total)
      import('@/vendor/Export2Excel').then(excel => {
        const relation = {
          '姓名': 'username',
          '工号': 'workNumber',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '转正日期': 'correctionTime',
          '聘用形式': 'formOfEmployment',
          '组织结构': 'departmentName'
        }
        const tHeader = Object.keys(relation)
        const data = res.rows.map(item => {
          const arr = tHeader.map(k => {
            // 获取到的是item 的值  relation[k] 英文文本
            const value = item[relation[k]]
            if (value && (k === '入职日期' || k === '转正日期')) {
              return moment(value).format('YYYY-MM-DD')
            }
            if (k === '聘用形式') {
              const obj = EmployeeEnum.hireType.find(item => item.id === value)
              return obj ? obj.value : ''
            }
            return value
          })
          return arr
        })
        excel.export_json_to_excel({
          // 表头 */
          header: tHeader,
          // 数据
          data,
          // 文件名
          filename: '员工数据',
          // 自动宽度
          autoWidth: true,
          // 后缀名
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    // 声场二维码  传递过来的参数 是url
    async addCode(url) {
      this.showCodeDialog = true
      await this.$nextTick() // 弹出对话框时dom 先让dom 渲染完
      qrcode.toCanvas(this.$refs.canvas, url) // 第一个参数是dom 第二个参数是图片的地址
    },

    // 给用户添加角色
    addRole(id) {
      this.userId = id
      this.showRoleDialog = true
    }

  }
}
</script>

<style>

</style>
